package com.adinall.dsp.core.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * 客户端信息工具类
 * 
 * @author 高万超
 * @version V1.0.0 $ 2016年2月3日 下午12:41:56
 */
public final class ClientUtils {

    /**
     * 获取客户端地址（IP）
     * 
     * @param request
     *            客户端请求
     * @return String 客户端地址（IP）
     */
    public static String getRemoteAddress(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");

        if (invalidIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (invalidIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (invalidIp(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (invalidIp(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (invalidIp(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    private static boolean invalidIp(String ip) {
        return CheckUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
    }

    /**
     * 客户端请求信息
     * 
     * @param request
     *            客户端请求
     * @return String 客户端请求信息
     */
    public static String contextPath(HttpServletRequest request) {

        StringBuffer buf = new StringBuffer();

        buf.append(request.getScheme() + "://");

        try {
            buf.append(InetAddress.getLocalHost().getHostAddress() + ":");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        buf.append(request.getServerPort());
        buf.append(request.getContextPath());

        return StringUtils.toString(buf);
    }

    /**
     * 客户端请求信息
     * 
     * @param request
     *            客户端请求
     * @return String 客户端请求信息
     */
    public static String servletPath(HttpServletRequest request) {
        return contextPath(request) + request.getServletPath();
    }
}